﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Text;
using System.Web.Security;
using System.Diagnostics;

/// <summary>
///Common 的摘要说明
/// </summary>
public class Common
{
    public Common()
    {
        //
        //TODO: 在此处添加构造函数逻辑
        //
    }


    /// <summary>
    /// DataTable转换为Json的格式
    /// </summary>
    /// <param name="dt">DataTable</param>
    /// <param name="withTableName">json数据是否需要带表名</param>
    /// <returns>Json string</returns>
    public static string DtToJson(DataTable dt, bool withTableName)
    {
        try
        {

            if (!DtIsNullOrEmpty(dt))
            {
                StringBuilder jsonBuilder = new StringBuilder();
                if (withTableName)
                {
                    jsonBuilder.Append("{\"");
                    jsonBuilder.Append(dt.TableName);
                    jsonBuilder.Append("\":");
                }
                jsonBuilder.Append("[");
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    jsonBuilder.Append("{");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        jsonBuilder.Append("\"");
                        jsonBuilder.Append(dt.Columns[j].ColumnName);
                        jsonBuilder.Append("\":\"");
                        jsonBuilder.Append(dt.Rows[i][j].ToString().Trim());
                        jsonBuilder.Append("\",");
                    }
                    jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                    jsonBuilder.Append("},");
                }
                jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                jsonBuilder.Append("]");
                if (withTableName) jsonBuilder.Append("}");
                return jsonBuilder.ToString();
            }
            else
            {
                return "[{\"rowsCount\":\"0\"}]";
            }
        }
        catch (Exception ex)
        {
            //Logger.WriteLog(string.Format("{0}_{1}_{2}", GetMethodLocateFileName(), GetMethodName(), ex.Message));
            return "";
        }
    }

    /// <summary>
    /// 判断DataTable是否为空
    /// </summary>
    /// <param name="dt">DataTable</param>
    /// <returns>空:true</returns>
    public static bool DtIsNullOrEmpty(DataTable dt)
    {
        if (dt != null)
        {
            if (dt.Rows.Count > 0)
            {
                return false;
            }
        }
        return true;
    }

    /// <summary>
    /// JS弹窗信息
    /// </summary>
    /// <param name="strMessage">Display Message</param>
    public static void AlertMessage(string strMessage)
    {
        string strJS = "<script language=javascript>alert('{0}');</script>";
        HttpContext.Current.Response.Write(string.Format(strJS, strMessage));

    }

    /// <summary>
    /// 弹出窗口并刷新页面
    /// </summary>
    /// <param name="strMessage"></param>
    /// <param name="strURL"></param>
    public static void AlertMessageAndRedirect(string strMessage, string strURL)
    {
        string strJS = "<script language=javascript>alert('{0}');location.href='{1}'</script>";
        HttpContext.Current.Response.Write(string.Format(strJS, strMessage, strURL));
    }

    /// <summary>
    /// JS提示并在主窗口跳转
    /// </summary>
    /// <param name="strMessage">Message</param>
    /// <param name="strURL">URL</param>
    public static void ParentRedirect(string strURL)
    {
        string strJS = "<script language=javascript>window.parent.location='{0}'</script>";
        HttpContext.Current.Response.Write(string.Format(strJS, strURL));

    }

    /// <summary>
    /// MD5加密
    /// </summary>
    /// <param name="strValue">加密字符串</param>
    /// <returns>string</returns>
    public static string MD5Encrypt(string strValue)
    {
        return FormsAuthentication.HashPasswordForStoringInConfigFile(strValue, "MD5").ToString();
    }



    /// <summary>
    /// 安全处理Request获取的值并转换成Interger
    /// </summary>
    /// <param name="strValue"></param>
    /// <returns></returns>
    public static int GetIntegerFromRequest(string strValue)
    {
        int valueToTry = 0;
        return int.TryParse(HttpUtility.HtmlEncode(strValue.Trim()), out valueToTry) ? valueToTry : -1;
    }


    #region
    /// <summary>
    /// 获取调用的方法所处的文件名（用于错误记录）
    /// </summary>
    /// <returns>文件名</returns>
    public static string GetMethodLocateFileName()
    {
        try
        {
            StackTrace stackTrace = new StackTrace(true);
            return stackTrace.GetFrame(1).GetFileName();
        }
        catch (Exception ex)
        {
            //Logger.WriteLog(string.Format("{0}_{1}_{2}", GetMethodLocateFileName(), GetMethodName(), ex.Message));
            return "";
        }
    }
    #endregion
}